package com.liuyk.commonlib.update;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.liuyk.commonlib.App;
import com.liuyk.commonlib.R;
import com.liuyk.commonlib.dialog.BaseDialog;
import com.liuyk.commonlib.help.UpdateHelp;
import com.liuyk.commonlib.network.DownloadCallBack;
import com.liuyk.commonlib.network.DownloadManager;
import com.liuyk.commonlib.utility.CommonIntentUtils;
import com.liuyk.commonlib.utility.PermissionUtils;

import java.io.File;

/**
 * APP更新
 * <p>
 * Created by liuyakui on 2020-02-22.
 */
public class UpdateDialog extends BaseDialog implements DownloadCallBack {
    private Activity activity;
    private ProgressBar progressBar;
    private String mApkUrl;
    private String mVersionName;
    private boolean isForce;
    private View mBottomContain;
    //更新进度百分比
    private TextView mUpdateBtn;
    //点击重试
    private TextView mDownContinue;
    private ImageView updateIcon;

    public UpdateDialog(Context context) {
        super(context);
        activity = (Activity) context;
        setDismiss(false);
        mBottomContain = findViewById(R.id.contain_b);
        progressBar = findViewById(R.id.app_update_progress);
        mUpdateBtn = findViewById(R.id.update_info_p);
        mDownContinue = findViewById(R.id.down_continue);
        updateIcon = findViewById(R.id.update_icon);
        mDownContinue.setOnClickListener(this);
    }

    public void setData(String apkUrl, String desc, String versionName, boolean isForce) {
        mApkUrl = apkUrl;
        mVersionName = versionName;
        if (TextUtils.isEmpty(mApkUrl)) {
            Toast.makeText(getContext(), "apk下载地址为空", Toast.LENGTH_SHORT).show();
        }

        TextView content = findViewById(R.id.content);
        content.setText(desc);
        //是否强制更新
        this.isForce = isForce;
        if (isForce) {
            findViewById(R.id.left_btn).setVisibility(View.GONE);
            findViewById(R.id.split).setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getId() == R.id.left_btn) {
            dismiss();
        }
        if (v.getId() == R.id.right_btn) {
            //避免重复点击
            v.setEnabled(false);
            v.postDelayed(new Runnable() {
                @Override
                public void run() {
                    v.setEnabled(true);
                }
            }, 200);
            checkWriteP();
        }
        //点击重试
        if (v.getId() == R.id.down_continue) {
            //避免重复点击
            v.setEnabled(false);
            v.postDelayed(new Runnable() {
                @Override
                public void run() {
                    v.setEnabled(true);
                }
            }, 200);
            mDownContinue.setVisibility(View.GONE);
            checkWriteP();
        }
    }

    private void checkWriteP() {
        boolean b = PermissionUtils.checkPermission(activity, PermissionUtils.Permission.PERMISSIONS_WRITE_EXTERNAL_STORAGE);
        PermissionUtils.requestPermission(activity, PermissionUtils.Permission.PERMISSIONS_WRITE_EXTERNAL_STORAGE, 101, new PermissionUtils.PermissionsCallBack() {

            @Override
            public void permissionsGranted(int requestCode) {
                //允许
                checkReadP();
            }

            @Override
            public void permissionsDenied(int requestCode) {

            }

            @Override
            public void noAsk(int requestCode) {

            }
        });
    }

    private void checkReadP() {
        PermissionUtils.requestPermission(activity, PermissionUtils.Permission.PERMISSIONS_READ_EXTERNAL_STORAGE, 102, new PermissionUtils.PermissionsCallBack() {

            @Override
            public void permissionsGranted(int requestCode) {
                //允许
                downloadApk();
            }

            @Override
            public void permissionsDenied(int requestCode) {

            }

            @Override
            public void noAsk(int requestCode) {

            }
        });
    }

    private void downloadApk() {
        //缓存检查
        File apkCacheFile = UpdateHelp.getApkCacheFile(getContext(), mVersionName);
        if (apkCacheFile != null && apkCacheFile.exists()) {
            CommonIntentUtils.goToInstallApk(getContext().getApplicationContext(), Uri.fromFile(apkCacheFile));
            if (!isForce) {
                dismiss();
            }
            return;
        }

        if (isForce) {
            //隐藏左右按钮
            mBottomContain.setVisibility(View.GONE);
            findViewById(R.id.bottom_split).setVisibility(View.GONE);

            //更新进度
            UpdateNotifyManager.getInstance(getContext()).show();
            DownloadManager.getInstance().download(mApkUrl, true, UpdateHelp.getApkDownloadFile(getContext(), mVersionName), this);
            progressBar.setVisibility(View.VISIBLE);
            long progress = DownloadManager.getInstance().getProgress(mApkUrl);
            long length = DownloadManager.getInstance().getLength(mApkUrl);
            progressBar.setMax((int) length);
            progressBar.setProgress((int) progress);
            mUpdateBtn.setVisibility(View.VISIBLE);
            return;
        }

        //如果不是强制更新，就启动后台service下载
        Intent intent = new Intent(activity, UpdateServer.class);
        intent.putExtra("apkUrl", mApkUrl);
        intent.putExtra("versionName", mVersionName);
        activity.startService(intent);
        Toast.makeText(App.context, "已转到后台下载", Toast.LENGTH_LONG).show();
        dismiss();
    }

    @Override
    protected int contentView() {
        return R.layout.app_update;
    }

    @Override
    public void downloadFail(String url, String reason) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                mDownContinue.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void downloading(String url, long length, long progress, int percent) {
        try {
            if (length > 0) {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setMax((int) length);
                        progressBar.setProgress((int) progress);
                        mUpdateBtn.setText("正在为您更新，请耐心等待(" + percent + "%)");
                    }
                });
                UpdateNotifyManager.getInstance(getContext()).updateProgress(
                        mApkUrl, mVersionName, (float) length, (float) progress);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void downloadSuccess(String url, File file) {
        UpdateNotifyManager.getInstance(getContext()).cancel();
        File renameFile = new File(UpdateHelp.getApkDir(), file.getName() + UpdateHelp.SUFFIX_APK);
        file.renameTo(renameFile);
        CommonIntentUtils.goToInstallApk(getContext().getApplicationContext(), Uri.fromFile(renameFile));

        //回到主线程
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                if (!isForce) {
                    dismiss();
                } else {
                    mBottomContain.setVisibility(View.VISIBLE);
                    findViewById(R.id.bottom_split).setVisibility(View.VISIBLE);

                    //隐藏更新进度
                    mUpdateBtn.setVisibility(View.GONE);
                    progressBar.setVisibility(View.GONE);
                }
            }
        });
    }

    public ImageView getUpdateIcon() {
        return updateIcon;
    }
}
